package com.wuyan.locationdog.ui.my


import android.graphics.Point
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMap
import com.amap.api.maps.AMap.OnCameraChangeListener
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.arcsoft.commonbase.base.BaseBindingActivity
import com.arcsoft.commonbase.ext.createEmptyView
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.wuyan.locationdog.R
import com.wuyan.locationdog.adapter.MarkPoiSearchListAdapter
import com.wuyan.locationdog.databinding.MarkMapActivityBinding
import com.wuyan.locationdog.help.DeviceHelp
import com.wuyan.locationdog.help.DogHelp
import com.wuyan.locationdog.ui.device.TrackDetailActivity
import com.wuyan.locationdog.util.maputil.MapHelp
import com.wuyan.locationdog.util.maputil.MapLifecycle
import com.wuyan.locationdog.viewmodel.DeviceViewModel

class MarkMapActivity : BaseBindingActivity<MarkMapActivityBinding>() {
    private var geocoderSearch: GeocodeSearch? = null
    private var searchLatlonPoint: LatLonPoint? = null
    private val mDeviceViewModel: DeviceViewModel by viewModels()
    private val mAdapter by lazy { MarkPoiSearchListAdapter(R.layout.item_mark_pio_search, null) }
    var isLocation: Boolean = true

    //声明定位回调监听器
    private var mLocationListener = AMapLocationListener { amapLocation ->
        if (amapLocation != null) {
            if (amapLocation.errorCode == 0) {
                //实时位置上报
                Log.e("map", "定位成功:$amapLocation")
                val latLng = LatLng(amapLocation.latitude, amapLocation.longitude)

                searchLatlonPoint = LatLonPoint(latLng.latitude, latLng.longitude)

                binding?.mapView?.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))


//                val latLng = LatLng(DeviceHelp.selectDeviceBeanContent.gaoDeLat, DeviceHelp.selectDeviceBeanContent.gaoDeLng)
//                binding.mapView.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))

            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e(
                    "map", "location Error, ErrCode:" + amapLocation.errorCode + ", errInfo:" + amapLocation.errorInfo
                )
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(MapLifecycle(binding.mapView, savedInstanceState))

    }


    override fun initData() {
        BarUtils.transparentStatusBar(this)
        binding.apply {
            btnBack.setOnClickListener {
                finish()
            }
            btnLocation.setOnClickListener {
                MapHelp.initLocation(mActivity, mLocationListener)

//                if (isLocation) {
//                    btnLocation.setImageResource(R.mipmap.map_location_device)
//
//                    MapHelp.initLocation(mActivity, mLocationListener)
//                } else {
//                    btnLocation.setImageResource(R.mipmap.map_location_my)
//
////                    val latLng = LatLng(deviceBeanContent.gaoDeLat, deviceBeanContent.gaoDeLng)
////                    mapView.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))
////                    MapHelp.setMapBounds(binding.mapView, mutableListOf(latLng))
//
//                }

                isLocation = !isLocation
            }
            recyclerView.apply {
                layoutManager = LinearLayoutManager(context)
                adapter = mAdapter.apply {
                    setOnItemClickListener { adapter, view, position ->
                        DogHelp.pointPoiItem = data[position]
                        ActivityUtils.startActivity(MarkSetNameActivity::class.java)
                    }
                }
            }

            mapView.map.setOnMapLoadedListener({ addMarkerInScreenCenter(mapView.map) })
            mapView.map.setOnCameraChangeListener(object : OnCameraChangeListener {
                override fun onCameraChange(cameraPosition: CameraPosition) {}
                override fun onCameraChangeFinish(cameraPosition: CameraPosition) {
                    geoAddress()
                    searchLatlonPoint = LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude)
                }
            })

        }
        MapHelp.initLocation(mActivity, mLocationListener)
        geocoderSearch = GeocodeSearch(this)
        geocoderSearch?.setOnGeocodeSearchListener(object : OnGeocodeSearchListener {
            override fun onRegeocodeSearched(result: RegeocodeResult?, rCode: Int) {
                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                    if (result?.getRegeocodeAddress() != null && result.regeocodeAddress.formatAddress != null) {
                        val address: String =
                            result.getRegeocodeAddress().getProvince() + result.getRegeocodeAddress().getCity() + result.getRegeocodeAddress()
                                .getDistrict() + result.getRegeocodeAddress().getTownship()
                        val firstItem = PoiItem("regeo", searchLatlonPoint, address, address)
                        Log.e("mark", "onRegeocodeSearched: " + firstItem.title)
//                        mAdapter.addData(firstItem)
                        doSearchQuery()
                    }
                } else {
                    Toast.makeText(mActivity, "error code is $rCode", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {

            }
        })

    }

    /**
     * 响应逆地理编码
     */
    fun geoAddress() {

        if (searchLatlonPoint != null) {
            val query = RegeocodeQuery(searchLatlonPoint, 200f, GeocodeSearch.AMAP) // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
            geocoderSearch?.getFromLocationAsyn(query)
        }
    }

    /**
     * 开始进行poi搜索
     */
    fun doSearchQuery() {
        currentPage = 0
        val query = PoiSearch.Query("", "", "") // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setCityLimit(true)
        query.setPageSize(20)
        query.setPageNum(currentPage)
        if (searchLatlonPoint != null) {
            val poiSearch = PoiSearch(this, query)
            poiSearch.setOnPoiSearchListener(object : PoiSearch.OnPoiSearchListener {
                override fun onPoiSearched(poiResult: PoiResult?, resultCode: Int) {

                    Log.e("mark", "onPoiSearched: " + poiResult?.pois.toString())
                    if (resultCode == AMapException.CODE_AMAP_SUCCESS) {
                        if (poiResult != null && poiResult.getQuery() != null) {
                            val pois = poiResult.getPois()
                            mAdapter.setNewInstance(pois)
                        } else {
                            Toast.makeText(mActivity, "无搜索结果", Toast.LENGTH_SHORT).show()
                        }
                    }
                }

                override fun onPoiItemSearched(p0: PoiItem?, p1: Int) {

                }
            })
            poiSearch.setBound(PoiSearch.SearchBound(searchLatlonPoint, 1000, true)) //
            poiSearch.searchPOIAsyn()
        }
    }

    override fun loadNetData() {
        super.loadNetData()

    }

    override fun observe() {
        super.observe()



        mDeviceViewModel.trackBean.observe(this) {
            DeviceHelp.instantTrackBeanContent = it.content
            ActivityUtils.startActivity(TrackDetailActivity::class.java)

        }

    }


    private fun addMarkerInScreenCenter(aMap: AMap) {
        val latLng: LatLng = aMap.getCameraPosition().target
        val screenPosition: Point = aMap.getProjection().toScreenLocation(latLng)
        val locationMarker = aMap.addMarker(
            MarkerOptions()
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_pin))
        )
        //设置Marker在屏幕上,不跟随地图移动
        locationMarker.setPositionByPixels(screenPosition.x, screenPosition.y)
        locationMarker.setZIndex(1f)
    }

}